const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const isDev = process.env.NODE_ENV === 'development'

const resolve = dir => path.join(__dirname, dir)

const networkInterfaces = require('os').networkInterfaces()
let ip = 'localhost'
let ytw = networkInterfaces['以太网']
let WLAN = networkInterfaces['WLAN']
if (WLAN) {
  ip = WLAN.find(item => item.family === 'IPv4').address
} else if (ytw) {
  ip = ytw.find(item => item.family === 'IPv4').address
}

const webpackConfig = {
  entry: isDev ? './src/main.js' : './packages/index.js',
  output: {
    path: path.resolve(__dirname, './dist/'),
    // publicPath: './',
    filename: isDev ? 'build.[hash].js' : 'index.js',
    library: 'rickyUtil', // 指定的就是你使用require时的模块名
    libraryTarget: 'umd', // 指定输出格式 // umd
    umdNamedDefine: true // 会对 UMD 的构建过程中的 AMD 模块进行命名。否则就使用匿名的 define
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ],
      },
      {
        test: /\.sass$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader?indentedSyntax'
        ],
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            scss: [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            sass: [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: `url-loader?limit=${Number.MAX_SAFE_INTEGER}`
      }
    ]
  },
  resolve: {
    alias: {
      '@': resolve('src'),
      vue$: 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {NODE_ENV: isDev ? '"development"' : '"production"'}
    })
  ],
  devtool: '#cheap-module-eval-source-map'
}

if (isDev) {
  webpackConfig.devServer = {
    host: ip,
    historyApiFallback: true,
    noInfo: true,
    overlay: true,
    hot: true,
  }
  webpackConfig.plugins.push(
    new HtmlWebpackPlugin({
      template: 'index.html'
    })
  )
}

module.exports = webpackConfig
